import 'dart:convert';

import 'package:ai_data_capture/bean/ConfigFileBean.dart';
import 'package:ai_data_capture/bean/StatueBean.dart';
import 'package:ai_data_capture/req/network_service.dart';

class ConfigApi {
  static Future<StatueBean?> getStatus() async {
    var res = await NetworkService.post(url: "config/get_run_status", map: {});
    return res?.getTypedData((map) => StatueBean.fromJson(map));
  }

  static Future<List<String>> getFunctions() async {
    var res = await NetworkService.post(url: 'config/get_functions', map: {});
    var list = res?.data;
    if (list is List) {
      return list.map((m) => "$m").toList();
    }
    return [];
  }

  static Future getConfig(String bean) async {
    var res = await NetworkService.post(
        url: 'config/get_config', map: {"type": bean});
    return res?.data;
  }

  static setConfig(type, content) async {
    var contentJson = jsonDecode(content);
    contentJson['type_'] = type;
    await NetworkService.post(url: 'config/set_config', map: contentJson);
  }

  static Future<List<ConfigFileBean>> getConfigFile() async {
    try {
      var res = await NetworkService.post(
          url: "config/get_config_file_list", map: {});
      return res?.getTypedList((m) => ConfigFileBean.fromJson(m)) ?? [];
    } catch (e) {
      return [];
    }
  }

  static addConfigFile(ConfigFileBean r, {bool isEdit = false}) async {
    Map<String, dynamic> map = r.toJson();
    if (!isEdit) {
      map.remove('id');
    }
    await NetworkService.post(url: "config/add_config_file", map: map);
  }

  static removeConfigFile(num? id) async {
    await NetworkService.post(
        url: "config/remove_config_file", map: {"id": id});
  }

  static run_single_step(String bean) async {
    await NetworkService.post(
        url: 'config/run_single_step', map: {"type": bean});
  }

  static Future<ConfigFileBean?> getConfigById(String? configId) async {
    var res = await NetworkService.post(
        url: 'config/get_config_file_by_id', map: {"id": configId});
    return res?.getTypedData((m) => ConfigFileBean.fromJson(m));
  }
}
